package com.api.ld.web;

import com.engine.ld.functions.sap.gyszsj.ZMM_VENDORDATA_MAINTAINProxy;
import com.engine.ld.optimize.Gyszsj;
import com.engine.ld.utils.DealXml;
import com.weaver.general.BaseBean;
import weaver.conn.RecordSet;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;

import java.util.Map;

/**
 * @author ZhangLei
 * @date 2021/7/1
 * 供应商主数据
 * 将数据传给SAP接口并接收其返回的参数
 */
public class GyszsjAction implements Action{
    public static final BaseBean bb = new BaseBean();

    @Override
    public String execute(RequestInfo requestInfo) {
        bb.writeLog("step0---------------");
        bb.writeLog("获取的requestID为："+requestInfo.getRequestid());
        return GyszsjHandle(requestInfo.getRequestid());
    }

    private String GyszsjHandle(String requestid){
        String back = "";
        Gyszsj gyszsj = new Gyszsj();
        bb.writeLog("step1---------------");

        try {
            ZMM_VENDORDATA_MAINTAINProxy pp = new ZMM_VENDORDATA_MAINTAINProxy();
            bb.writeLog("step2---------------");
            String SAPBackXml = pp.getZMM_VENDORDATA_MAINTAIN_PortType().ZMM_VENDORDATA_MAINTAIN(gyszsj.createGyszsj(requestid));
//            String SAPBackXml = pp.getZMM_VENDORDATA_MAINTAIN_PortType().ZMM_VENDORDATA_MAINTAIN(normXml);
//            bb.writeLog("传给SAP接口的xml文件是:"+normXml);
            bb.writeLog("SAP的返回结果是："+SAPBackXml);
            Map<String, Object> sapBackMap = new DealXml().XmlResultMap(SAPBackXml);
            bb.writeLog("sapBackMap解析xml的返回结果是"+sapBackMap);
            String type = sapBackMap.get("TYPE").toString();
            String message  = sapBackMap.get("MESSAGE").toString();
            message = message.contains("'")?message.replace("'","''"):message;
            bb.writeLog("解析后，type:"+type+";message:"+message);

            boolean saptodatabase = saptodatabase(type, message,requestid);
            bb.writeLog("SAP返回结果添加到数据库："+saptodatabase);
            if ("E".equals(type)){
                bb.writeLog("SAP返回结果为E，其中Message为："+message);
                back=Action.FAILURE_AND_CONTINUE;
            }else {
                back = Action.SUCCESS;
            }
        } catch (Exception e) {
            e.printStackTrace();
            bb.writeLog("方法发生了错误，信息为："+e);
        }
        bb.writeLog("方法结束后back的值为："+back);
        return back;
    }

    /*将sap返回的结果存入数据库*/
    private boolean saptodatabase(String type, String message,String requestid){
        String sql = "UPDATE formtable_main_109 SET TYPE='"+type+"',MESSAGE='"+message+"' WHERE requestId="+requestid;
        RecordSet rs = new RecordSet();
        return rs.executeUpdate(sql);
    }

}
